package pushmsg

import (
    "encoding/json"
	"bytes"
	"errors"
	"net/http"
	"io/ioutil"
	"github.com/astaxie/beego"
)

/*
{"msg_id":"666666666","content":[{"id":"7777777","topic":"OrderPay","partner_id":11111,"store_id":22222,"order_id":"27587324275","created_time":"2013-10-08 16:36:53"},{"id":"8888888","topic":"OrderPay","partner_id":11111,"store_id":22222,"order_id":"27587324275","created_time":"2013-10-08 16:36:53"}]}

{"msg_id":"666666666","rsp":"success"}
*/


type PushMsgHeader struct {
    MsgId    string  `json:"msg_id"` 
}

type PushMsgBody struct {
	Id          string `json:"id,omitempty"` 
	Topic       string `json:"topic"`
	PartnerId   int64  `json:"partner_id"`
	StoreId     int64  `json:"store_id"`
	OrderId     string `json:"order_id"`
	CreatedTime string `json:"created_time"`
}

type PushMessage struct {
    //*PushMsgHeader
	MsgId    string  `json:"msg_id"` 
	Content []PushMsgBody `json:"content"`
}

func PackPushMessge(pushMessage *PushMessage)([]byte, error) {
	msgJson, err := json.Marshal(pushMessage)
	if err != nil {
	   return msgJson, err
	}
	return msgJson, nil
}

/*
{"msg_id":"7777777","topic":"OrderPay","partner_id":11111,"store_id":22222,"order_id":"27587324275","created_time":"2013-10-08 16:36:53"}

{"msg_id":"666666666","rsp":"success"}
*/

type PushMessageNew struct {
	MsgId       int64  `json:"msg_id"` 
	Topic       string `json:"topic"`
	PartnerId   int64  `json:"partner_id"`
	StoreId     int64  `json:"store_id"`
	OrderId     string `json:"order_id"`
	CreatedTime string `json:"created_time"`
}

func PackPushMessgeNew(pushMessageNew *PushMessageNew)([]byte, error) {
	msgJson, err := json.Marshal(pushMessageNew)
	if err != nil {
	   return msgJson, err
	}
	return msgJson, nil
}

func HttpPushMessge(url, sendContent string) error {
	beego.Debug("req url:", url, "content:", sendContent)
	body := bytes.NewBuffer([]byte(sendContent))
	res, err := http.Post(url, "application/json;charset=utf-8", body)
	if err != nil {	
	   beego.Debug("Post:", err.Error())
	   return err
	}
	result, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {	
	   beego.Debug("ReadAll:", err.Error())
	   return err
	}
	beego.Debug("rsp result:", string(result))
	httpRsp := struct {
		MsgId string `json:"msg_id"`
		Rsp   string `json:"rsp"`
	}{}
	if err := json.Unmarshal(result, &httpRsp); err != nil {
	    beego.Debug("Unmarshal:", err.Error())
		return err
	}
	if httpRsp.Rsp != "success" {
	    beego.Debug("response is error")
		return errors.New("response is error")
	}
	return nil
}


    
	
	